package com.example.contactcloud;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.contactcloud.R;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class AddContact extends Activity {

	Contact contact = new Contact();
	static final String EXTRA_MESSAGE="";
	String loginStatus = "";
	private static final String PHP_LOAD = "http://softeng.cs.uwosh.edu/students/baurj00/PHPLoad.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(LoginActivity.globalTheme);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_contact);
		
		Intent i = getIntent();
		loginStatus = i.getStringExtra(EXTRA_MESSAGE);
		
		Spinner spinner = (Spinner)findViewById(R.id.groupSpinner2);
		spinner.setSelection(contact.getGroup(),true);
		
		new GetAllGroupsTask().execute();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_add_contact, menu);
		return true;
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void addClicked(View v){
		TextView txtName = (TextView) findViewById(R.id.editName);
		String name = txtName.getText().toString();
		
		if (name.equals("")){
    		Context context = getApplicationContext();
    		CharSequence text = "Your Contact Must Have A Name!";
    		int duration = Toast.LENGTH_SHORT;
    		
    		Toast toast = Toast.makeText(context, text, duration);
    		toast.show();
		}
		else{
		
		TextView txtAddress = (TextView) findViewById(R.id.editAddress);
		String address = txtAddress.getText().toString();
		
		TextView txtCell = (TextView) findViewById(R.id.editGroup1);
		String cell = txtCell.getText().toString();
		
		TextView txtAlternate = (TextView) findViewById(R.id.editAlternate);
		String alt = txtAlternate.getText().toString();
		
		TextView txtEmail = (TextView) findViewById(R.id.editEmail);
		String email = txtEmail.getText().toString();
		
		TextView txtComments = (TextView) findViewById(R.id.editGroup2);
		String comments = txtComments.getText().toString();
		
		Spinner spinner = (Spinner)findViewById(R.id.groupSpinner2);
		int group = spinner.getSelectedItemPosition();
		
		Contact newContact = new Contact();
		newContact.setName(name);
		newContact.setAddress(address);
		newContact.setCell(cell);
		newContact.setAlt(alt);
		newContact.setEmail(email);
		newContact.setComments(comments);
		newContact.setGroup(group);
		
		new AddContactTask().execute(newContact);
		
		if(loginStatus.equals("false")){
			close();
		}
		
		new UpdateTime().execute();
		}
	}
	
	private void close()
	{		
		this.finish();
	}
	
	private class UpdateTime extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			
			ContactsDataSource cds = new ContactsDataSource(AddContact.this);
			
			cds.open();
			
			cds.updateTime();
			
			cds.close();
			return null;
		}

		
	}
	
	
	private class AddContactTask extends AsyncTask<Contact, Void, Contact>{

		@Override
		protected Contact doInBackground(Contact... contacts) {
			
			ContactsDataSource cds = new ContactsDataSource(AddContact.this);
			
			cds.open();
			
			for(Contact c : contacts){
				cds.addContact(c);
			}
			
			cds.close();
			return contacts[0];
		}
		protected void onPostExecute(Contact c)
		{
			if (!loginStatus.equals("false")){
				new uploadContact().execute(c);
			}
		}
	}
	
	private class GetAllGroupsTask extends AsyncTask<Void, Integer, ArrayList<Group>>{

		@Override
		protected ArrayList<Group> doInBackground(Void... nothing) {
			
			ContactsDataSource cds3 = new ContactsDataSource(AddContact.this);
			
			cds3.open();
			
			ArrayList<Group> groups = cds3.getAllGroups();
			
			cds3.close();
			
			return groups;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Group> groupList) {
    		Spinner spinner = (Spinner) findViewById(R.id.groupSpinner2);
    		ArrayAdapter<Group> adapter =  new ArrayAdapter<Group>(AddContact.this, android.R.layout.simple_spinner_dropdown_item, groupList);
    		spinner.setAdapter(adapter);        
        }
		
	}
	
	private class uploadContact extends AsyncTask<Contact, Void, String> 
	{
		@Override
		protected String doInBackground(Contact... arg0) 
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				
				JSONArray allJSONContacts = new JSONArray();
				
				String all = null;

					JSONObject jContact = new JSONObject();
					Contact temp = arg0[0];
					
					ContactsDataSource cds3 = new ContactsDataSource(AddContact.this);
					
					cds3.open();
					
					long id = cds3.getContactByName(temp.getName());
					
					cds3.close();
					
					try
					{
						jContact.put("id", id);
						jContact.put("name", temp.getName());
						jContact.put("address", temp.getAddress());
						jContact.put("cell", temp.getCell());
						jContact.put("alt", temp.getAlt());
						jContact.put("email", temp.getEmail());
						jContact.put("comments", temp.getComments());
						jContact.put("group", temp.getGroup());
						allJSONContacts.put(0, jContact);				
					}catch(Exception ex)
					{
						System.err.println("Cannot create #" + 0 + " JSON Contact");
					}
				
				all = allJSONContacts.toString();
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_LOAD);
				//HttPost httpost2 = new HttpPost()
 				
				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
				c.add(new BasicNameValuePair("json", all));
				
				try
				{				
					httppost.setEntity(new UrlEncodedFormEntity(c));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String rep = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					System.out.println(e.getMessage());
				}
			}
		
			return "";
		}
		
		 protected void onPostExecute(String temp)
		 {
			close();
		 }

	}

}

